package com.bw.module_mine.ui.login

import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.bw.lib_common.IntentData
import com.bw.lib_common.appContext
import com.bw.lib_common.base.BaseActivity
import com.bw.lib_common.base.BaseFragment
import com.bw.lib_common.base.state.RequestEvent
import com.bw.lib_common.getAttrValue
import com.bw.lib_common.utils.ToastUtils
import com.bw.lib_common.utils.ValidUtil
import com.bw.module_mine.R
import com.bw.module_mine.databinding.FragmentAccountLoginBinding
import com.bw.module_mine.ui.login.viewmodel.LoginViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class AccountLoginFragment : BaseFragment<LoginViewModel, FragmentAccountLoginBinding>() {
    private val mViewModel: LoginViewModel by activityViewModels()//和activity公用同一个viewmodel。实现通信
    override val mLayoutResId: Int
        get() = R.layout.fragment_account_login
    private lateinit var mNavController: NavController
    private var mLoginAgreement: Boolean = false //是否勾选同意
    override fun initView() {
        super.initView()
        //设置当前正在显示的fragment
        mViewModel.setShowingFragmentTag(AccountLoginFragment::class.java.simpleName)
        mNavController = Navigation.findNavController(mBinding.root)
        initAgreementCheckBox(mLoginAgreement)
        initAgreementView()
    }

    override fun initData() {
        super.initData()
        mBinding.viewModel = mViewModel
    }

    override fun initListener() {
        super.initListener()
        mBinding.apply {
            //隐私政策
            vChecked.setOnClickListener {
                mLoginAgreement = !mLoginAgreement
                initAgreementCheckBox(mLoginAgreement)
            }
            btnLogin.setOnClickListener {
                checkPhone()
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.requestLoginEvent_.collect{
                    when (it) {
                        is RequestEvent.Success -> {
                            setLoadingViewVisible(false)
                            //跳转到登录成功页面
                            (requireActivity() as LoginActivity).handleLoginSuccess()

                        }
                        is RequestEvent.Error -> {
                            setLoadingViewVisible(false)
                            ToastUtils.showShort(requireActivity(),it.msg)
                        }
                        is RequestEvent.Loading -> {
                            setLoadingViewVisible( true)
                        }
                        else -> {}
                    }
                }
            }
        }
        mBinding.tvForgetPassword.setOnClickListener {
            mNavController.navigate(R.id.action_accountLoginFragment_to_forgetPwdFragment)
        }
    }

    private fun checkPhone() {
        val phone = mViewModel.phone.value
        val password = mViewModel.password.value
        if (!mLoginAgreement) {
            (activity as BaseActivity<*, *>?)?.dismissKeyboard()
            ToastUtils.showShort(context, "请先勾选同意《用户协议》和《隐私政策》")
//            mPopupAgreement.show(mBinding.btnCheck)
            return
        }

        if (!ValidUtil.phoneNumberValid(phone)) {
            ToastUtils.showShort(context, "手机号码长度错误")
            return
        }
        //验证密码不为空
        if (password.isNullOrEmpty()){
            ToastUtils.showShort(context, "请输入密码")
            return
        }
        mViewModel.loginByAccount(phone, password)
    }
    //隐私政策Check背景切换
    private fun initAgreementCheckBox(checked: Boolean) {
        if (!checked) {
            mBinding.btnCheck.background = ContextCompat.getDrawable(appContext, R.mipmap.icon_uncheck)
        } else {
//            mPopupAgreement.dismiss()
            mBinding.btnCheck.background = ContextCompat.getDrawable(appContext, R.mipmap.icon_checked)
        }
    }
    //用户协议 隐私政策
    private fun initAgreementView() {
        val colorMain = getAttrValue(requireContext()!!, com.bw.lib_common.R.attr.colorTheme)
        val userAgreement = "《用户协议》"
        val privacyPolicy = "《隐私政策》"
        val content = "阅读并同意$userAgreement 和$privacyPolicy"
        val spannableStringBuilder = SpannableStringBuilder(content)
        val userAgreementStart = content.indexOf(userAgreement)
        val userAgreementEnd = userAgreementStart + userAgreement.length

        val privacyPolicyStart = content.indexOf(privacyPolicy)
        val privacyPolicyEnd = privacyPolicyStart + privacyPolicy.length

        spannableStringBuilder.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
//                CommonWebActivity.jumpUserAgreement()
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(requireContext(), colorMain)
                ds.isUnderlineText = false
            }

        }, userAgreementStart, userAgreementEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        spannableStringBuilder.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
//                CommonWebActivity.jumpPrivacyAgreement()
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(requireContext(), colorMain)
                ds.isUnderlineText = false
            }

        }, privacyPolicyStart, privacyPolicyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

        mBinding.tvAgreement.highlightColor = Color.TRANSPARENT
        mBinding.tvAgreement.text = spannableStringBuilder
        mBinding.tvAgreement.movementMethod = LinkMovementMethod.getInstance()
    }
}